package com.example.baselibrary.wigits

import android.app.Activity
import android.app.Dialog
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import java.lang.ref.WeakReference
import java.util.Stack

class XUIDialogManager private constructor() : LifecycleObserver {
    companion object {
        @Volatile
        private var instance: XUIDialogManager? = null

        fun getInstance(): XUIDialogManager {
            return instance ?: synchronized(this) {
                instance ?: XUIDialogManager().also { instance = it }
            }
        }
    }

    // 使用WeakReference存储Context，避免内存泄漏
    private var contextRef: WeakReference<Context>? = null
    private val dialogStack = Stack<WeakReference<Dialog>>()

    /**
     * 初始化管理器
     */
    fun init(context: Context) {
        this.contextRef = WeakReference(context)

        // 如果是 AppCompatActivity，注册生命周期观察者
        if (context is AppCompatActivity) {
            context.lifecycle.addObserver(this)
        }
    }

    /**
     * 显示普通对话框
     */
    fun showNormalDialog(
        title: String?,
        message: String,
        positiveText: String = "确定",
        negativeText: String? = null,
        onPositiveClick: (() -> Unit)? = null,
        onNegativeClick: (() -> Unit)? = null
    ): MaterialDialog? {
        val context = contextRef?.get() ?: return null
        if (context is Activity && (context.isFinishing || context.isDestroyed)) return null

        val builder = MaterialDialog.Builder(context)
            .apply {
                title?.let { title(it) }
                content(message)
                positiveText(positiveText)
                onPositive { _, _ -> onPositiveClick?.invoke() }

                negativeText?.let {
                    negativeText(it)
                    onNegative { _, _ -> onNegativeClick?.invoke() }
                }
            }

        val dialog = builder.build()

        dialog.setOnCancelListener {
            removeDialogFromStack(dialog)
        }

        addDialogToStack(dialog)
        dialog.show()

        return dialog
    }


    fun <T> showListDialog(
        title: String?,
        items: List<T>,
        itemTransformer: (T) -> String = { it.toString() },
        onItemClick: (Int, T) -> Unit
    ): MaterialDialog? {
        val context = contextRef?.get() ?: return null
        if (context is Activity && (context.isFinishing || context.isDestroyed)) return null

        val stringItems = items.map(itemTransformer).toTypedArray()
        val dialog = MaterialDialog.Builder(context)
            .apply {
                title?.let { title(it) }
                items(*stringItems)
                itemsCallback { _, _, position, _ ->
                    onItemClick(position, items[position])
                }
            }
            .build()

        dialog.setOnCancelListener {
            removeDialogFromStack(dialog)
        }

        addDialogToStack(dialog)
        dialog.show()

        return dialog
    }


    fun <T> showSingleChoiceDialog(
        title: String?,
        items: List<T>,
        selectedIndex: Int = -1,
        itemTransformer: (T) -> String = { it.toString() },
        onChoice: (Int, T) -> Unit
    ): MaterialDialog? {
        val context = contextRef?.get() ?: return null
        if (context is Activity && (context.isFinishing || context.isDestroyed)) return null

        val stringItems = items.map(itemTransformer).toTypedArray()
        val builder = MaterialDialog.Builder(context)
            .apply {
                title?.let { title(it) }
                items(*stringItems)
                itemsCallbackSingleChoice(selectedIndex) { _, _, which, _ ->
                    onChoice(which, items[which])
                    true
                }
            }

        val dialog = builder.build()

        dialog.setOnCancelListener {
            removeDialogFromStack(dialog)
        }

        addDialogToStack(dialog)
        dialog.show()

        return dialog
    }


    /**
     * 显示输入对话框
     */
    fun showInputDialog(
        title: String?,
        hint: String? = null,
        inputType: Int? = null,
        onInput: (String) -> Unit
    ): MaterialDialog? {
        val context = contextRef?.get() ?: return null
        if (context is Activity && (context.isFinishing || context.isDestroyed)) return null

        val builder = MaterialDialog.Builder(context)
            .apply {
                title?.let { title(it) }
                input(hint, "") { _, input ->
                    onInput(input.toString())
                }
                inputType?.let {
                    inputType(it)
                }
            }

        val dialog = builder.build()

        dialog.setOnCancelListener {
            removeDialogFromStack(dialog)
        }

        addDialogToStack(dialog)
        dialog.show()

        return dialog
    }


    /**
     * 添加对话框到栈中
     */
    private fun addDialogToStack(dialog: Dialog) {
        cleanupDialogReferences()
        dialogStack.push(WeakReference(dialog))
    }

    /**
     * 从栈中移除指定对话框
     */
    private fun removeDialogFromStack(dialog: Dialog) {
        val iterator = dialogStack.iterator()
        while (iterator.hasNext()) {
            val dialogRef = iterator.next()
            if (dialogRef.get() == dialog) {
                iterator.remove()
                break
            }
        }
    }

    /**
     * 清理已销毁的对话框引用
     */
    private fun cleanupDialogReferences() {
        val iterator = dialogStack.iterator()
        while (iterator.hasNext()) {
            val dialogRef = iterator.next()
            if (dialogRef.get() == null) {
                iterator.remove()
            }
        }
    }

    /**
     * 关闭所有对话框
     */
    fun dismissAllDialogs() {
        dialogStack.forEach { dialogRef ->
            dialogRef.get()?.let { dialog ->
                if (dialog.isShowing) {
                    try {
                        dialog.dismiss()
                    } catch (e: Exception) {
                        // 忽略异常，可能对话框已经关闭
                    }
                }
            }
        }
        dialogStack.clear()
    }

    /**
     * 在Activity onDestroy时调用，防止内存泄漏
     */
    fun onDestroy() {
        dismissAllDialogs()
        contextRef?.clear()
        contextRef = null
    }

    /**2
     * Lifecycle事件：当Activity销毁时自动清理资源
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onActivityDestroy() {
        onDestroy()
    }

    /**
     * 获取当前管理的对话框数量
     */
    fun getDialogCount(): Int {
        cleanupDialogReferences()
        return dialogStack.size
    }
}
